package piano;

/* 
 * Author: rendy.jr
 * Date: Jun 10, 2011
 * 6.005 Elements of Software Construction
 * Rendy Bambang Junior
 * rendy.jr@gmail.com
 * 
 * Recorder responsible for :
 * - record actions
 * - play actions
 * 
 */

import java.util.Vector;

import midi.Midi;
import piano.ActionElement.ActionType;

public class Recorder {
	private Vector<ActionElement> actions;
	private boolean recording = false;
	private boolean playing = false;
	private long startRecordTime = 0;
	private Piano piano;
	
	public Recorder(){
		piano = new Piano();
		actions = new Vector<ActionElement>();
	}
	
	public void startRecording(){
		if(!recording){
			actions.clear();
			recording = true;
			startRecordTime = System.currentTimeMillis();
		}
	}
	
	public void stopRecording(){
		recording = false;
	}
	
	public void startPlaying(){
		if(!playing){
			playing = true;
			for(int i = 0; i < actions.size(); i++){
				if(actions.get(i).getAction()==ActionType.ADD){
					piano.play(actions.get(i).getKey());
					if(i<actions.size()-1){
						Midi.wait((int)actions.get(i+1).getTimeStamp()-(int)actions.get(i).getTimeStamp());
					}
				}
				else{
					piano.stop(actions.get(i).getKey());
				}
			}
		}
	}
	
	public void stopPlaying(){
		playing = false;
	}
	
	public void addAction(ActionType a, char k){
		if(recording)
			actions.add(new ActionElement(a, k, System.currentTimeMillis()-startRecordTime));
	}
	
	public boolean isRecording(){
		return recording;
	}
	
	public boolean isPlaying(){
		return playing;
	}
	
	public Vector<ActionElement> getActions(){
		return actions;
	}
}
